package keyword

/**
 * 懒加载
 */
class Lazy {

    /**
     * 伴生对象
     */
    companion object {

        /**
         *  默认 （默认mode为LazyThreadSafetyMode.SYNCHRONIZED）
         */
        val def by lazy {
            println("def lazy ${Thread.currentThread()}，${System.currentTimeMillis()}")
            Thread.sleep(10)
            "def ${Thread.currentThread()}，${System.currentTimeMillis()}"
        }

        /**
         * 同步懒加载(线程安全)
         */
        val sync by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            println("synchronized lazy ${Thread.currentThread()}，${System.currentTimeMillis()}")
            Thread.sleep(10)
            "sync ${Thread.currentThread()}，${System.currentTimeMillis()}"
        }

        /**
         * 多线程同步执行
         */
        val pub by lazy(LazyThreadSafetyMode.PUBLICATION) {
            println("publication lazy ${Thread.currentThread()}，${System.currentTimeMillis()}")
            Thread.sleep(10)
            "pub ${Thread.currentThread()}，${System.currentTimeMillis()}"
        }

        /**
         * 总单个线程执行，普通模式(非线程安全)
         */
        val none by lazy(LazyThreadSafetyMode.NONE) {
            println("none lazy ${Thread.currentThread()}，${System.currentTimeMillis()}")
            Thread.sleep(10)
            "none ${Thread.currentThread()}，${System.currentTimeMillis()}"
        }
    }
}

fun main(args: Array<String>) {
    var i = 10
    while (i > 0) {
        Thread(Runnable {
            println(Lazy.pub)
        }).start()
        i--
    }
}